package com.example.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author zhangW
 * @create 2025-01-09-14:21
 */
@RestControllerAdvice
public class GloablReesponse implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //对所有controller返回层进行处理
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof Response<?>){
            return body;
        }
        else if(body == null){
            return new Response(200,"请求成功");
        }
        else {
            // 否则，将返回值封装为统一的 ApiResponse 格式
            return new  Response(200,"请求成功",body);
        }
    }
}
